import csv
import re

import time
import traceback

from bs4 import BeautifulSoup

from common.request import seleniumutil
from config import config


def to_search_page(browser):
    to_main(browser)
    browser.find_element_by_css_selector("#tabs > div.tabs-header > div.tabs-wrap > ul > li.tabs-first").click()
    browser.switch_to.frame("iframeRightId")
    switch_selected_frame(browser)


def to_search_page1(browser, ifr):
    to_main(browser)
    browser.switch_to.frame(ifr)


def to_detail_page(browser):
    to_main(browser)
    browser.find_element_by_css_selector("#tabs > div.tabs-header > div.tabs-wrap > ul > li.tabs-last").click()
    browser.switch_to.frame("iframeRightId")
    switch_selected_frame(browser)


def to_main(browser):
    browser.switch_to.default_content()
    # browser.implicitly_wait(10)


def close_detail_page(browser):
    to_main(browser)
    browser.find_element_by_css_selector(
        "#tabs > div.tabs-header > div.tabs-wrap > ul > li.tabs-last > a.tabs-close").click()


def ret_switch_select_frame(browser):
    to_main(browser)
    panals = browser.find_elements_by_css_selector(".tabs-panels .panel")
    for panal in panals:
        if "<div class=\"panel\" style=\"display: block; width:" in panal.get_attribute("outerHTML"):
            iframe = panal.find_element_by_tag_name("iframe")
            return iframe.id


def switch_selected_frame(browser):
    to_main(browser)
    panals = browser.find_elements_by_css_selector(".tabs-panels .panel")
    for panal in panals:
        if "<div class=\"panel\" style=\"display: block; width:" in panal.get_attribute("outerHTML"):
            iframe = panal.find_element_by_tag_name("iframe")
            browser.switch_to.frame(iframe)
            # browser.implicitly_wait(10)


def get_text(soup, selector):
    try:
        aaa = ""
        selector = selector.replace("nth-child", "nth-of-type")
        t0 = time.clock()
        fff = soup.select(selector)
        if fff:
            aaa = fff[0].text

        # txt = browser.find_element_by_css_selector(selector).text
        t1 = time.clock()
        # print("%s: %s s" % (selector, (str(t1 - t0))))

        return aaa
    except Exception as e:
        if "no such element" in str(e):
            return ""
        return "获取失败" + str(e)




USERNAME = ""


def login(browser, username, pwd):
    global USERNAME
    USERNAME = username
    logout(browser)
    url = "https://www.sudai9.com/manage/index/indexlogin.html?brand=29"
    browser.get(url)
    browser.find_element_by_css_selector("#kefu_number").send_keys(username)
    browser.find_element_by_css_selector("#smscode").clear()
    browser.find_element_by_css_selector("#kefu_password").clear()
    browser.find_element_by_css_selector("#kefu_password").send_keys(pwd)

    # # print("账号%s,输入验证码:" % username);
    # smscode = "1234"  # "#input()

    browser.find_element_by_css_selector("#smscode").send_keys("1234")
    browser.find_element_by_css_selector(
        "body > div.container-fluid.login_box > div.container > form > div:nth-child(4) > button").click()
    browser.implicitly_wait(5)
    if browser.page_source.__contains__("获取验证码"):
        print("aaa")


def logout(browser):
    try:
        # to_main(browser)
        # browser.find_element_by_css_selector(
        #     "body > div.panel.layout-panel.layout-panel-north > div > div.pull-right.nav_daohang > ul > li.shezhi > div > ul > li:nth-child(4) > a").click()
        browser.get("https://www.sudai9.com/manage/index/indexlogout.html")
    except:
        pass


def 我的客户(browser,menu_name):
    # https://www.sudai9.com/manage/kefu_clients/index.html
    # 先打开我的客户
    to_main(browser)
    browser.implicitly_wait(3)

    # _easyui_tree_2 > span.tree-title


    menus = browser.find_elements_by_css_selector("#tree > li >.tree-node > span.tree-title")
    for m in menus:
        if "我的客户" in m.text:
            m.click()
            break
    search_iframe = ret_switch_select_frame(browser)
    # 关闭第一个,因为自己的新打开的



    data_csvfile = open(config.PATH_DESKTOP + "/我的客户%s.csv" % USERNAME, "a", newline='', encoding='utf-8')
    data_writer = csv.writer(data_csvfile)
    errorfile = open(config.PATH_DESKTOP + "error%s.txt" % USERNAME, "w")
    errorfile.writelines("开始了")
    headers = None

    # soup = BeautifulSoup(browser.page_source, 'html.parser')

    for i in range(1, 1000):

        trs = browser.find_elements_by_css_selector("#lk_content > table > tbody > tr")

        for tr in trs:
            try:
                tr_html = tr.get_attribute("innerHTML")
                if "Open" not in tr_html:
                    continue
                tr.find_elements_by_css_selector("td")[2].click()

                tds=tr.find_element_by_tag_name("td")

                userinfo = {}
                userinfo["姓名"] = tds[0].text
                userinfo["手机号"] = tds[0].text
                userinfo["来源"] = tds[0].text
                userinfo["申请城市"] = tds[0].text
                userinfo["学历"] = tds[0].text
                userinfo["户籍"] = tds[0].text
                userinfo["年龄"] =tds[0].text
                userinfo["婚姻"] = tds[0].text
                userinfo["身份证"] =tds[0].text
                userinfo["性别"] = tds[0].text
                userinfo["毕业院校"] = tds[0].text
                userinfo["客户公司"] = tds[0].text
                userinfo["申请额度"] = tds[0].text
                userinfo["来源类型"] = tds[0].text
                userinfo["名下房产情况"] = get_text(soup, "#infomation-info10 > div:nth-child(2) > ul > li > div.showdetailsinfo")
                userinfo["名下车产情况"] = get_text(soup,
                                              "#infomation-info10 > div:nth-child(3) > ul > li:nth-child(1) > div.showdetailsinfo")
                userinfo["汽车类型"] = get_text(soup,
                                            "#infomation-info10 > div:nth-child(3) > ul > li:nth-child(2) > div.showdetailsinfo")
                userinfo["汽车归属地"] = get_text(soup,
                                             "#infomation-info10 > div:nth-child(3) > ul > li:nth-child(3) > div.showdetailsname")
                userinfo["汽车使用年限"] = get_text(soup,
                                              "#infomation-info10 > div:nth-child(3) > ul > li:nth-child(4) > div.showdetailsinfo")
                userinfo["汽车价值"] = get_text(soup,
                                            "#infomation-info10 > div:nth-child(3) > ul > li:nth-child(5) > div.showdetailsinfo")
                userinfo["车险公司"] = get_text(soup,
                                            "#infomation-info10 > div:nth-child(3) > ul > li:nth-child(6) > div.showdetailsinfo")
                userinfo["当前保单缴费次数"] = get_text(soup,
                                                "#infomation-info10 > div:nth-child(3) > ul > li:nth-child(7) > div.showdetailsinfo")
                userinfo["车辆状态"] = get_text(soup,
                                            "#infomation-info10 > div:nth-child(3) > ul > li:nth-child(8) > div.showdetailsinfo")
                userinfo["BD有无保单"] = get_text(soup,
                                              "#infomation-info10 > div:nth-child(4) > ul > li:nth-child(1) > div.showdetailsinfo")
                userinfo["保单公司"] = get_text(soup,
                                            "#infomation-info10 > div:nth-child(4) > ul > li:nth-child(2) > div.showdetailsinfo")
                userinfo["年缴费额"] = get_text(soup,
                                            "#infomation-info10 > div:nth-child(4) > ul > li:nth-child(3) > div.showdetailsinfo")
                userinfo["保单状态"] = get_text(soup,
                                            "#infomation-info10 > div:nth-child(4) > ul > li:nth-child(4) > div.showdetailsinfo")
                userinfo["已缴次数"] = get_text(soup,
                                            "#infomation-info10 > div:nth-child(4) > ul > li:nth-child(5) > div.showdetailsinfo")
                userinfo["两年内最严重的逾期"] = get_text(soup,
                                                 "#infomation-info10 > div:nth-child(5) > ul > li:nth-child(1) > div.showdetailsinfo")
                userinfo["一年内最严重的逾期"] = get_text(soup,
                                                 "#infomation-info10 > div:nth-child(5) > ul > li:nth-child(2) > div.showdetailsinfo")
                userinfo["半年内最严重的逾期"] = get_text(soup,
                                                 "#infomation-info10 > div:nth-child(5) > ul > li:nth-child(3) > div.showdetailsinfo")
                userinfo["微粒贷额度"] = get_text(soup,
                                             "#infomation-info10 > div:nth-child(5) > ul > li:nth-child(4) > div.showdetailsinfo")
                userinfo["芝麻信用分"] = get_text(soup,
                                             "#infomation-info10 > div:nth-child(5) > ul > li:nth-child(5) > div.showdetailsinfo")
                userinfo["信用卡情况"] = get_text(soup,
                                             "#infomation-info10 > div:nth-child(6) > ul > li:nth-child(1) > div.showdetailsinfo")
                userinfo["贷记卡总额总额度"] = get_text(soup,
                                                "#infomation-info10 > div:nth-child(6) > ul > li:nth-child(2) > div.showdetailsinfo")
                userinfo["贷记卡当前使用额度"] = get_text(soup,
                                                 "#infomation-info10 > div:nth-child(6) > ul > li:nth-child(3) > div.showdetailsinfo")
                userinfo["贷记卡近半年使用额度"] = get_text(soup,
                                                  "#infomation-info10 > div:nth-child(6) > ul > li:nth-child(4) > div.showdetailsinfo")
                userinfo["单张贷记卡最高负债率"] = get_text(soup,
                                                  "#infomation-info10 > div:nth-child(6) > ul > li:nth-child(5) > div.showdetailsinfo")
                userinfo["有无信用贷款"] = get_text(soup,
                                              "#infomation-info10 > div:nth-child(6) > ul > li:nth-child(6) > div.showdetailsinfo")
                userinfo["客户星级"] = browser.find_element_by_css_selector("#stars > option[selected=selected]").text
                userinfo["状态"] = browser.find_element_by_css_selector("#status > option[selected=selected]").text

                memo_eles = browser.find_elements_by_css_selector("#hisul > li")
                memo_jsons = []
                for m in memo_eles:
                    memo_jsons.append(m.text)
                userinfo["备注"] = str(memo_jsons)


                if not headers:
                    headers = r.keys()
                    data_writer.writerow(headers)
                data_writer.writerow([r[h] for h in headers])

                close_detail_page(browser)
            except Exception as e:
                errorfile.writelines("----------------------------------------------")
                errorfile.writelines(tr.text)
                errorfile.writelines(str(e))
        if browser.find_elements_by_css_selector("#pagination > a.next"):
            try:
                browser.find_element_by_css_selector("#pagination > a.next").click()
            except Exception as e:
                traceback.print_exc()
        else:
            break
        data_csvfile.flush()
    data_csvfile.flush()
    data_csvfile.close()
    errorfile.close()




def execute(browser, username, pwd):
    # https://www.sudai9.com/manage/kefu_clients/index.html
    # 先打开我的客户

    url = "https://www.sudai9.com/manage/index/indexlogin.html?brand=29"
    print(username)
    login(browser, username, pwd)

    try:
        我的客户(browser)
        logout(browser)
    except Exception as e:
        traceback.print_exc()

def eee():
    # users = [["18621040101", "111111"]]
    users = [
        ["18217393308", "111111"],
        ["13916840167", "111111"],
        ["19901783149", "987654"],
        ["13127723517", "111111"],
        ["18930706628", "111111"],
        ["18017246963", "111111"],
        ["18930500521", "18930500521"],
        ["13166169956", "zhudaiwang168"],
        ["13817352064", "111111"],
        ["15821123041", "lxx6521364"],
        ["15821529937", "111111"],
        ["13482162767", "111111"],
        ["18616263558", "111111"],
        ["18516245203", "111111"],
        ["17521710626", "zhudaiwang168"],
        ["15026671273", "zhudaiwang168"],
        ["13816250180", "zhudaiwang168"],
        ["13310108595", "sudaiwang168"],
        ["13564317926", "zhudaiwang"],
        ["19921151164", "sudaiwang168"], ["15021328552", "222222"]]


    browser = seleniumutil.chrome_driver_remote()

    for u in users:
        logout(browser)
        execute(browser, u[0], u[1])

if __name__ == "__main__":
    eee()